/// <reference path="chart.component.d.ts" />
import {AfterViewInit, Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {interval} from 'rxjs';
import {take} from 'rxjs/internal/operators';

@Component({
  selector: 'ng-tools-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.scss']
})
export class ChartComponent implements OnInit, AfterViewInit, OnDestroy {
  @Output() ready = new EventEmitter();
  @Input() size: { width: string; height: string };
  id: string;
  private chart;

  constructor() {
    this.id = `echart-${Math.floor(Math.random() * 10 ** 16)}`; // 随机生成id，有极低概览重复
  }

  ngOnInit() {
  }

  ngOnDestroy(): void {
    /**
     * 组件生命周期结束时释放echarts资源
     * */
    return this.chart && this.chart.dispose();
  }

  setOption(options: any) {
    this.chart.setOption(options);
  }

  ngAfterViewInit(): void {
    const ob = interval(20).pipe(take(500)).subscribe(() => {
      const elem = document.getElementById(this.id);
      if (elem) {
        ob.unsubscribe();
        this.chart = echarts.init(elem);
        this.ready.emit();
      }
    });
  }
}
